<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { http } from '../utils/http'
import { API_CONFIG } from '../config/api'

type Post = {
  id: number
  summary: string
  writer: string
  updateTime: string
  likeNum?: number
  commentNum?: number
}

const router = useRouter()

// Post接口已在api服务中定义，这里移除重复定义

const posts = ref<Post[]>([])
const loading = ref(true)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const sortBy = ref('updateTime')
const sortOrder = ref('desc')

// 模拟数据
const mockPosts = [
  { id: 1, summary: "Vue 3 新特性详解：Composition API 的使用指南", writer: "技术达人", updateTime: "2024-01-15" },
  { id: 2, summary: "前端开发中的性能优化技巧分享", writer: "前端工程师", updateTime: "2024-01-14" },
  { id: 3, summary: "TypeScript 高级类型系统深度解析", writer: "TS专家", updateTime: "2024-01-13" },
  { id: 4, summary: "React vs Vue：选择哪个框架？", writer: "框架对比", updateTime: "2024-01-12" },
  { id: 5, summary: "CSS Grid 布局完全指南", writer: "CSS大师", updateTime: "2024-01-11" },
  { id: 6, summary: "JavaScript 异步编程最佳实践", writer: "JS专家", updateTime: "2024-01-10" },
  { id: 7, summary: "Webpack 5 配置详解", writer: "构建工具", updateTime: "2024-01-09" },
  { id: 8, summary: "Node.js 服务端开发入门", writer: "后端新手", updateTime: "2024-01-08" },
  { id: 9, summary: "Python 数据分析实战", writer: "数据科学家", updateTime: "2024-01-07" },
  { id: 10, summary: "机器学习算法详解", writer: "AI专家", updateTime: "2024-01-06" },
  { id: 11, summary: "Docker 容器化部署指南", writer: "运维工程师", updateTime: "2024-01-05" },
  { id: 12, summary: "微服务架构设计模式", writer: "架构师", updateTime: "2024-01-04" },
  { id: 13, summary: "数据库优化技巧总结", writer: "DBA", updateTime: "2024-01-03" },
  { id: 14, summary: "Git 版本控制最佳实践", writer: "开发工具", updateTime: "2024-01-02" },
  { id: 15, summary: "移动端开发技术选型", writer: "移动开发", updateTime: "2024-01-01" }
]

const fetchPosts = async () => {
  loading.value = true
  try {
    console.log('请求网关服务：VITE_API_BASE_URL', import.meta.env.VITE_API_BASE_URL)
    // 调用真实API服务
    const response = await http.get(`${API_CONFIG.BASE_URL}/posts`, {
      page: currentPage.value,
      pageSize: pageSize.value,
      sortBy: sortBy.value,
      sortOrder: sortOrder.value
    })
    console.log('获取帖子列表成功:', response)
    
    posts.value = response.posts || []
    total.value = response.total || 0
  } catch (error) {
    console.error('获取帖子列表失败:', error)
    // 如果API调用失败，使用模拟数据作为降级方案
    ElMessage.warning('网络请求失败，显示模拟数据')
    posts.value = mockPosts
    total.value = 100
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchPosts()
}

const handleSortChange = () => {
  currentPage.value = 1
  fetchPosts()
}

const goToPost = (id: number) => {
  router.push(`/posts/${id}`)
}

onMounted(() => {
  fetchPosts()
})
</script>

<template>
  <div class="post-list">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <h1>GL论坛</h1>
      <el-button type="primary" @click="router.push('/create-post')">
        <el-icon><Plus /></el-icon>
        发布新帖子
      </el-button>
    </div>

    <!-- 排序和筛选 -->
    <el-card class="filter-card">
      <div class="filter-content">
        <div class="sort-section">
          <span>排序方式：</span>
          <el-select v-model="sortBy" @change="handleSortChange" style="width: 150px; margin-right: 10px;">
            <el-option label="更新时间" value="updateTime" />
            <el-option label="点赞数" value="likeNum" />
            <el-option label="评论数" value="commentNum" />
          </el-select>
          <el-button-group>
            <el-button 
              :type="sortOrder === 'desc' ? 'primary' : ''" 
              @click="sortOrder = 'desc'; handleSortChange()"
            >
              降序
            </el-button>
            <el-button 
              :type="sortOrder === 'asc' ? 'primary' : ''" 
              @click="sortOrder = 'asc'; handleSortChange()"
            >
              升序
            </el-button>
          </el-button-group>
        </div>
      </div>
    </el-card>

    <!-- 帖子列表 -->
    <div class="posts-list">
      <el-card v-for="post in posts" :key="post.id" class="post-row" @click="goToPost(post.id)">
        <div class="post-row-content">
          <span class="post-title">{{ post.summary }}</span>
          <span class="post-meta">
            <span class="post-author"><el-icon><User /></el-icon>{{ post.writer }}</span>
            <span class="post-time"><el-icon><Clock /></el-icon>{{ post.updateTime }}</span>
            <el-button text size="small" @click.stop="goToPost(post.id)">
              <el-icon><View /></el-icon>详情
            </el-button>
          </span>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePageChange(1)"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<style scoped>
.post-list {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  box-sizing: border-box;
  padding: 0 10px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.page-header h1 {
  margin: 0;
  color: #333;
  font-size: 1.2em;
}

.filter-card {
  margin-bottom: 16px;
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sort-section {
  display: flex;
  align-items: center;
  gap: 8px;
}

.sort-section span {
  color: #666;
  font-weight: 500;
}

.posts-list {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 24px;
}

.el-card.post-row {
  width: 100% !important;
  margin: 0 !important;
  max-width: none !important;
  box-sizing: border-box;
}

.post-row {
  cursor: pointer;
  transition: box-shadow 0.2s;
  padding: 8px 8px;
  font-size: 0.96em;
  background: #fff;
}

.post-row:hover {
  box-shadow: 0 4px 20px rgba(0,0,0,0.08);
}

.post-row-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}

.post-title {
  flex: 1 1 0;
  font-weight: 500;
  color: #222;
  font-size: 0.98em;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-right: 12px;
}

.post-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 0.9em;
  color: #888;
  flex-shrink: 0;
}

.post-author, .post-time {
  display: flex;
  align-items: center;
  gap: 3px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}
</style>